Learn Technologies
Angular 8 Login Form

Angular 8 with ASP.Net Core Tutorial part 5 Login Form

In this part of Tutorial, we will learn how to make:

  • Login Form.
  • Email and Password Validations.
  • Login action Web API

You can find the code source on GitHub:
– Web API: https://github.com/AlphaTechstudios/Forms.WebAPI/tree/angular_tuto_part_5
– Angular: https://github.com/AlphaTechstudios/Forms/tree/Angular_tuto_part_5

Add Login Form

Last time, we have already created the sign-in component. Let’s navigate to sign-in.component.html and add 2 fields for Email and password:

<form [formGroup]="signInForm" (ngSubmit)="onSubmit()">
    <div class="card text-center w-50 mx-auto mt-5">
        <div class="card-header bg-primary">
            <h3>Sign In</h3>
        </div>

        <div class="card-body">
            <div [hidden]="!showError" class="alert-danger alert">
                <span >Login or Password is incorrect!</span>
            </div>
            <div class="form-group row d-flex justify-content-center align-items-center">
                <label for="email" class="col-form-label col-sm-2 text-right">Email:</label>
                <div class="col-sm-5">
                    <input type="text" formControlName="email" class="form-control" />
                    <div *ngIf="signInData.email.invalid && (signInData.email.dirty || signInData.email.touched)"
                        class="alert-danger">
                        <span *ngIf="signInData.email.errors.required">Email is required!</span>
                        <span *ngIf="signInData.email.errors.email">Email must be a valid address!</span>
                    </div>
                </div>
            </div>
            <div class="form-group row d-flex justify-content-center align-items-center">
                <label for="password" class="col-form-label col-sm-2 text-right">Password:</label>
                <div class="col-sm-5">
                    <input type="password" formControlName="password" class="form-control" />
                    <div *ngIf="signInData.password.invalid && (signInData.password.dirty || signInData.password.touched)"
                        class="alert-danger">
                        <span *ngIf="signInData.password.errors.required">Password is required!</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="card-footer">
            <button [disabled]="isLoading" class="btn btn-primary mr-2">Sign In</button>
        </div>

    </div>
</form>

Like the signUp form, the Email input is required and it must be a valid address. However, the password is only required.
We used the directive [hidden] in order to bind the visibility of error message whether the Login action returns error from Web Api.

When user submits the data, we lock the sign up button, by using the directive [disable]. This condition

In the sign-in.component.ts, we have to initialize the login form in onInit method by using the formBuilder and put the validation rules for each Input field.

ngOnInit() {
    this.signInForm = this.formBuilder.group({
      email: ['', [Validators.email, Validators.required]],
      password: ['', Validators.required]
    });
  }

Finally, we define the onSubmit method. Check if the signInForm is valid and there is no login request in progress.
After that, call the usersService for login action and switch the response, we make the redirection to Home page (login with success), else we show the famous message “Login or password is incorrect!”.

onSubmit(){
    if(this.signInForm.invalid || this.isLoading){
      return ;
    }

    this.isLoading = true;
    // Call user service for login.
    this.usersService.login(this.signInForm.value).subscribe(x => {
      this.isLoading = false;
      // redirect to Home page.
      this.router.navigate(["/Home"]);
    },
      error =>{
        this.isLoading = false;
        this.showError = true;
      });
  }

Web API Side

In the Forms.Models project, we create the LoginModel class.

using System;
using System.Collections.Generic;
using System.Text;

namespace Forms.Models
{
    public class LoginModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

In the Forms.Managers project, we create the UserModelExtensions class.
The goal of this class is to define extension method, in order to clean the userModel object’s password for security reason.

using Forms.Models;
using System.Collections.Generic;
using System.Linq;

namespace Forms.Managers.Commun
{
    public static class UserModelExtensions
    {
        public static IEnumerable<UserModel> WithoutPassword(this IEnumerable<UserModel> users)
        {
            return users.Select(x => x.WithoutPassword());
        }

        public static UserModel WithoutPassword(this UserModel userModel)
        {
            userModel.Password = null;
            return userModel;
        }

    }
}

Now, let’s define in IUsersManager the contract for Login method.

using Forms.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace Forms.Managers.Interfaces
{
    public interface IUsersManager
    {
        UserModel GetUserById(int id);
        IEnumerable<UserModel> GetUsers();
        long InsertUser(UserModel userModel);
        UserModel Login(LoginModel loginModel);
    }
}

In UsersManager.cs, we create the Login method body.

 public UserModel Login(LoginModel loginModel)
        {
            var user = usersRepository.Get(x => x.Email == loginModel.Email && x.Password == loginModel.Password).SingleOrDefault();

            if(user != null)
            {
                return user.WithoutPassword();
            }
            return null;
        }

Finally, we add the Login action in UsersController.cs.
Don’t forget to put the HttpPost(“login”) attribute, in order to differentiate the different httpPost actions.
If the user is null (not found), return BadRequest response with message.

[HttpPost("login")]
        public IActionResult Login([FromBody] LoginModel loginModel)
        {
            var user = usersManager.Login(loginModel);
            if(user == null)
            {
                return BadRequest(new { message = "Login or password is incorrect" });
            }
            return Ok(user);
        }

Run the project by executing the command :

ng serve --proxy-config proxy.conf.json

Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x